<?php
declare (strict_types = 1);

namespace app\common\chat\command;

use app\kefuapi\service\WorkermanService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;

class ChatCommand extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('chatCommand')
            ->addArgument('action', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon（守护进程）方式启动')
            ->setDescription('the chat command');
    }

    protected function execute(Input $input, Output $output)
    {

        $action = $input->getArgument('action') ? : 'start';

        // 重新构造命令行参数,以便兼容workerman的命令
        global $argv;
        $argv = ['think', $action];

        if($input->hasOption('d')){
            $argv[] = '-d';
        }

        try {
            // 创建一个Worker监听20090端口，使用websocket协议通讯
            $worker = new Worker("websocket://0.0.0.0:20090");
            // 启动进程数量
            $worker->count = 1;

            // 使用类方法作为回调
            $service = new WorkermanService();

            $worker->onWorkerStart = array($service, 'onWorkerStart');
            $worker->onConnect = array($service, 'onConnect');
            $worker->onMessage =  array($service, 'onMessage');
            $worker->onClose = array($service, 'onClose');
            $worker->onWorkerStop = array($service, 'onWorkerStop');
            $worker->onWorkerReload = array($service, 'onWorkerReload');
            $worker->onError = array($service, 'onError');

            // 运行workerman
            Worker::runAll();

            // 指令输出
            $output->writeln("chat service {$action} success !");

        }catch (\Exception $e){
            $output->warning($e->getMessage());
        }

    }
}
